<template>
	<xn-form-container title="图片库" :width="1300" v-model:open="open" :destroy-on-close="true" @close="onClose">
		<div class="flex h-[70vh] gap-1">
			<div class="w-2/6 rounded-md border border-gray-200 border-solid">
				<div class="p-2 flex border-b border-b-gray-200" style="border-bottom-style: solid">
					<a-input-search
						v-model:value="searchGroupName"
						placeholder="搜索分组名"
						enter-button
						allowClear
						@search="getCateTree"
					/>
					<a-button type="primary" @click="eduImgGroupFormRef.onOpen({ sortCode: 99, parentPath: ['0'] })">
						<template #icon>
							<plus-outlined />
						</template>
						添加
					</a-button>
				</div>
				<div class="h-[64vh] overflow-hidden overflow-y-auto custom-scrollbar">
					<a-spin tip="加载中..." :spinning="groupTreeLoading">
						<a-tree
							:auto-expand-parent="autoExpandParent"
							:tree-data="groupTree"
							blockNode
							:fieldNames="{ children: 'children', title: 'name', key: 'id' }"
							@select="selectTree"
							v-if="groupTree.length > 0"
						>
							<template #title="record">
								<div class="w-80 line-clamp-1" :title="record.name" v-if="record.id === '0'">{{ record.name }}</div>
								<a-popover placement="rightTop" v-else>
									<template #content>
										<a-space>
											<a-button :icon="h(EditOutlined)" title="编辑" @click="eduImgGroupFormRef.onOpen(record)" />
											<a-button
												v-if="record.parentPath.length <= 1"
												:icon="h(PlusOutlined)"
												@click="
													eduImgGroupFormRef.onOpen({ sortCode: 99, parentPath: [...record.parentPath, record.id] })
												"
												title="新增"
											/>
											<a-button danger :icon="h(DeleteOutlined)" title="删除" />
										</a-space>
									</template>
									<div class="w-80 flex justify-between">
										<div class="w-48 line-clamp-1" :title="record.name">
											{{ record.name }}
										</div>
										<a-space>
											<a-typography-text class="line-clamp-1 w-14" :title="`小计:${record.imgCount}`"
												>共：{{ record.imgCount }}
											</a-typography-text>
											<a-typography-text class="line-clamp-1 w-14" type="secondary" :title="`顺序:${record.sortCode}`"
												>{{ record.sortCode }}
											</a-typography-text>
										</a-space>
									</div>
								</a-popover>
							</template>
						</a-tree>

						<a-empty class="my-20" v-else />
					</a-spin>
				</div>
			</div>
			<div class="w-4/6 rounded-md border border-gray-200 border-solid">
				<div class="p-2 flex border-b border-b-gray-200" style="border-bottom-style: solid">
					<a-input-search
						v-model:value="searchImgName"
						placeholder="搜索图片"
						enter-button
						allowClear
						@search="searchHandler"
					/>
					<a-space>
						<a-button type="default" :disabled="null == group" @click="eduStockImgUploadRef.onOpen(group)">
							<template #icon>
								<cloud-upload-outlined />
							</template>
							上传图片
						</a-button>
						<a-button type="primary" @click="useImage" :disabled="selectedImgList.length === 0">
							使用选中的图片</a-button
						>

					</a-space>
				</div>
				<a-spin tip="加载中..." :spinning="imgListLoading">
					<div class="h-[58vh] overflow-hidden overflow-y-auto custom-scrollbar">
						<div
							class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3 p-2 justify-items-center"
							v-if="imgList.length > 0"
						>
							<edu-stock-image-card
								v-for="item in imgList"
								:selected="item.selected"
								:image="item"
								@eye="eyeHandler"
								@edit="editHandler"
								@click="selectedHandler(item)"
								@delete="deleteHandler"
							></edu-stock-image-card>
						</div>
						<a-empty class="my-20" v-else />
					</div>
				</a-spin>

				<div class="h-[6vh] flex items-center justify-center">
					<a-pagination
						v-model:current="imgSearchParam.current"
						v-model:page-size="imgSearchParam.size"
						showSizeChanger
						show-quick-jumper
						:total="imgSearchParam.total"
						@change="changePage"
					/>
				</div>
			</div>
		</div>
	</xn-form-container>
	<edu-img-group-form ref="eduImgGroupFormRef" @successful="imgGroupSuccessful"></edu-img-group-form>

	<edu-stock-img-upload ref="eduStockImgUploadRef" @successful="eduStockImgUploadSuccessful"></edu-stock-img-upload>
	<a-image
		:width="200"
		:style="{ display: 'none' }"
		:preview="{
			visible: imagePreview.visible,
			onVisibleChange: setImageVisible
		}"
		:src="imagePreview.src"
	/>

	<edu-stock-image-form ref="eduStockImageFormRef" @successful="imgEditSuccessful"></edu-stock-image-form>
	<contextHolder />
</template>

<script setup name="eduImgStock">
	import { h } from 'vue'
	import { cloneDeep } from 'lodash-es'
	import { required } from '@/utils/formRules'
	import eduCourseCateApi from '@/api/biz/eduCourseCateApi'
	import eduImgGroupApi from '@/api/biz/eduImgGroupApi'
	import eduImgApi from '@/api/biz/eduImgApi'
	import EduImgGroupForm from '@/components/EduImgStock/edu-img-group-form.vue'
	import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons-vue'
	import EduStockImageCard from '@/components/EduImgStock/edu-stock-image-card.vue'
	import EduStockImgUpload from '@/components/EduImgStock/edu-stock-img-upload.vue'
	import EduStockImageForm from '@/components/EduImgStock/edu-stock-image-form.vue'
	import { message, Modal } from 'ant-design-vue'

	const [modal, contextHolder] = Modal.useModal()

	// 定义 props
	const props = defineProps({
		count: {
			type: Number,
			required: false,
			default: 1
		}
	})

	// 抽屉状态
	const open = ref(false)
	const emit = defineEmits({ successful: null })
	const eduImgGroupFormRef = ref()
	const eduStockImageFormRef = ref()
	const eduStockImgUploadRef = ref()
	const selectedImgList = computed(() => imgList.value.filter((img) => img.selected))

	const expandedKeys = ref([])
	const searchValue = ref('')
	const autoExpandParent = ref(true)

	const groupTree = ref([])
	// 表单数据

	const searchGroupName = ref('')
	const searchImgName = ref('')
	const submitLoading = ref(false)

	// 打开抽屉
	const onOpen = (record) => {
		getCateTree()
		getImgList()
		open.value = true
	}
	// 关闭抽屉
	const onClose = () => {
		open.value = false
	}

	// 验证并提交数据
	const onSubmit = () => {
		console.log(formData.value)
		formRef.value
			.validate()
			.then(() => {
				submitLoading.value = true
				const formDataParam = cloneDeep(formData.value)
				eduCourseCateApi
					.eduCourseCateSubmitForm(formDataParam, formDataParam.id)
					.then(() => {
						onClose()
						emit('successful')
					})
					.finally(() => {
						submitLoading.value = false
					})
			})
			.catch(() => {})
	}

	// 课程分类树
	const groupTreeLoading = ref(false)
	const getCateTree = () => {
		groupTreeLoading.value = true
		eduImgGroupApi
			.eduImgGroupTree({ level: 2, includeTop: true, name: searchGroupName.value })
			.then((tree) => {
				tree[0].selectable = false
				groupTree.value = tree
			})
			.finally(() => {
				groupTreeLoading.value = false
			})
	}

	// 分组编辑完成
	const imgGroupSuccessful = () => {
		getCateTree()
	}
	// 图片上传成功
	const eduStockImgUploadSuccessful = () => {
		getCateTree()
	}

	const group = ref(null)
	const selectTree = (selectedKeys, { selected, node }) => {
		console.log(selected, node, selectedKeys)
		if (selected) {
			// treeExpandedKeys.value = [...treeExpandedKeys.value,node.id]
			group.value = node

			console.log([...node.parentPath, node.id])
			imgSearchParam.value.groupId = node.id
			getImgList()
		} else {
			// treeExpandedKeys.value = treeExpandedKeys.value.filter(id=>id !== node.id)
			group.value = null
			imgSearchParam.value.groupId = ''
			getImgList()
		}
	}

	const imgSearchParam = ref({
		current: 1,
		size: 10,
		name: '',
		total: 0,
		groupId: ''
	})
	//  图片库
	const imgList = ref([])
	const imgListLoading = ref(false)
	const getImgList = () => {
		imgListLoading.value = true
		eduImgApi
			.eduImgPage(imgSearchParam.value)
			.then((res) => {
				imgList.value = res.records
				imgSearchParam.value.total = res.total
			})
			.finally(() => {
				imgListLoading.value = false
			})
	}

	// 分页
	const changePage = (page, pageSize) => {
		imgSearchParam.value.current = page
		imgSearchParam.value.size = pageSize
		getImgList()
	}

	const searchHandler = () => {
		imgSearchParam.value.name = searchImgName.value
		imgSearchParam.value.current = 1
		getImgList()
	}
	// 图片预览
	const imagePreview = ref({ visible: false, src: '' })

	const setImageVisible = (visible) => {
		imagePreview.value.visible = visible
	}

	// 图片预览
	const eyeHandler = (e) => {
		imagePreview.value = { visible: true, src: e.url }
	}

	// 图片编辑
	const editHandler = (e) => {
		eduStockImageFormRef.value.onOpen(e)
	}
	// 图片编辑回调
	const imgEditSuccessful = () => {
		imgSearchParam.value.current = 1
		getImgList()
	}
	const deleteHandler = (e) => {
		modal.confirm({
			title: `是否确认删除${e.name}?`,
			icon: h(ExclamationCircleOutlined),
			async onOk() {
				let res = await eduImgApi.eduImgDelete([{ id: e.id }])
				imgEditSuccessful()
			},
			onCancel() {
				console.log('Cancel')
			}
		})
	}
	const selectedHandler = (item) => {
		item.selected = !item.selected
		if (selectedImgList.value.length > props.count) {
			item.selected = false
			message.warning(`最多只能选择${props.count}图片`)
		}
	}

	const useImage = () => {
		open.value = false
		emit(
			'successful',
			selectedImgList.value.map((item) => item.url)
		)
	}


	// 抛出函数
	defineExpose({
		onOpen
	})
</script>

<style scoped lang="less"></style>
